

import 'dart:collection';

import 'package:flutter/material.dart';
import 'package:my_flutter_app/main.dart';
import 'package:my_flutter_app/provider_lib.dart';

class Item {
  Item(this.price, this.count);

  double price;
  int count;
}

class CartModel extends ChangeNotifier {

  final List<Item> _items = [];

  UnmodifiableListView<Item> get items => UnmodifiableListView(_items);

  double get totalPrice => _items.fold(0, (value, item) => value + item.count * item.price);

  void add(Item item) {
    _items.add(item);
    notifyListeners();
  }
}

class ProviderRoute extends StatefulWidget{
  @override
  _ProviderRouteState createState() => _ProviderRouteState();
}

class _ProviderRouteState extends State<ProviderRoute> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("ProviderRoute"),),
      body: Center(
        child: ChangeNotifierProvider<CartModel> (
          data: CartModel(),
          child: Builder(
            builder: (context) {
              return Column(
                children: <Widget>[
                  Consumer<CartModel>(builder: (context, cart) => Text("总价：${cart.totalPrice}")),
                  Builder(
                    builder: (context) {
                      print(MY_TAG_1 + "RaisedButton build");
                      return RaisedButton(
                        child: Text("添加商品"),
                        onPressed: () {
                          ChangeNotifierProvider.of<CartModel>(context, listen: false).add(Item(20.0, 1));
                        },
                      );
                    },
                  ),
                ],
              );
            },
          ),
        ),
      ),
    );
  }
}